<?php

/**
 * Description of msgbox_model
 *
 * @author terminus
 */
class Msgbox_model extends CI_Model {

    private $tableName = 'msgbox';

    public function __construct() {
        parent::__construct();
    }

    public function getAll($only_count = 0, $limit = '', $offset = '') {
        if (1 != $only_count) {
            if ($limit > 0) {
                $this->db->limit($limit);
                if ($offset > 0) {
                    $this->db->limit($limit, $offset);
                }
            }
        }
        $result = $this->db->order_by('post_time', 'DESC')->get($this->tableName);
        if ($result->num_rows() > 0) {
            if (1 == $only_count) {
                return $result->num_rows();
            }
            return $result->result();
        }
        return FALSE;
    }

    public function getMsg($id) {
        $where['id'] = $id;

        $result = $this->db->get_where($this->tableName, $where, 1);
        if ($result->num_rows() > 0) {
            return $result->row();
        }
        return FALSE;
    }

    public function addMsg($user_opn_id, $platform_opn_id, $msgtype_id, $content, $post_time, $wx_msg_id) {
        $set = array(
            'user_opn_id' => $user_opn_id,
            'platform_opn_id' => $platform_opn_id,
            'msgtype_id' => $msgtype_id,
            'content' => $content,
            'post_time' => $post_time,
            'wx_msg_id' => $wx_msg_id
        );

        $this->db->insert($this->tableName, $set);
        $id = $this->db->insert_id();
        if ($id > 0) {
            return $id;
        }
        return FALSE;
    }

    public function setMsg($id, $reply_msgtype_id, $reply_content) {
        $where['id'] = $id;
        $set = array(
            'reply_msgtype_id' => $reply_msgtype_id,
            'reply_content' => $reply_content,
            'reply_time' => time()
        );

        if (TRUE === $this->db->update($this->tableName, $set, $where, 1)) {
            return TRUE;
        }
        return FALSE;
    }

    public function delMsg($id) {
        $where['id'] = $id;

        $this->db->delete($this->tableName, $where, 1);
        if ($this->db->affected_rows() > 0) {
            return TRUE;
        }
        return FALSE;
    }

}
